import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { Form, Checkbox, Field, Button } from '@teamix/ui';
import { Section, Header, Content } from '@alife/devops-ui';
import { enterPage, Perf } from 'utils/track';
import ListLoading from 'atComponents/ListLoading';
import * as actions from '../actions/index';
import intl from '../../../../../../../../../locale';

const formItemLayout = {
  labelCol: {
    fixedSpan: 6,
  },

  wrapperCol: {
    span: 16,
  },
};

class Root extends Component {
  constructor(props) {
    super(props);
    this.field = new Field(this);
  }

  static propTypes = {
    formSubmit: PropTypes.func,
    getGroupSettingData: PropTypes.func,
  };

  state = {
    loading: true,
    submitting: false,
    disableSaveBtn: true,
    defaultSettings: {},
  };

  componentDidMount() {
    document.title = intl.get({
      id: 'code-assets.groupPermissions.containers.root.CodeGroupManagement',
      defaultMessage: '代码组管理 · 云效 Codeup',
    });

    window.onbeforeunload = null;
    this.props.getGroupSettingData((result) => {
      if (result.group_creator_role[result.group_creator_role.length - 1] === 40) {
        result.group_creator_role[result.group_creator_role.length - 1] = 60;
      } else if (result.group_creator_role[result.group_creator_role.length - 1] !== 60) {
        result.group_creator_role.push(60);
      }

      this.field.setValues(result);
      this.setState({
        defaultSettings: result,
        loading: false,
      });
    });
    this.props.getOrgAliasName();

    enterPage('Organization-Settings-Group Permissions', {
      sendPerf: false,
    });
  }

  formChange = () => {
    let changed = false;
    const fieldNames = this.field.getNames();
    for (let i = 0; i < fieldNames.length; i++) {
      const name = fieldNames[i];
      const defaultSetting = this.state.defaultSettings[name];
      const nowSetting = this.field.getValue(name);
      if (defaultSetting instanceof Array && nowSetting instanceof Array) {
        if (defaultSetting.sort().toString() !== nowSetting.sort().toString()) {
          changed = true;
        }
      } else if (typeof defaultSetting === 'boolean') {
        if (nowSetting === undefined) {
          changed = defaultSetting === true;
        } else {
          changed = defaultSetting !== nowSetting;
        }
      } else {
        changed = defaultSetting !== nowSetting;
      }
      if (changed === true) {
        break;
      }
    }
    this.setState({
      disableSaveBtn: !changed,
    });

    if (changed) {
      window.onbeforeunload = function () {
        return intl.get({
          id: 'code-assets.groupPermissions.containers.root.AreYouSureYouWant',
          defaultMessage: '确定离开此页面？',
        });
      };
    } else {
      window.onbeforeunload = null;
    }
  };

  handleSave = () => {
    if (this.state.submitting) return;
    this.setState({ submitting: true });
    this.field.validate((errors) => {
      if (!errors) {
        const formData = this.field.getValues();
        this.props.formSubmit(formData, () => {
          this.setState({
            submitting: false,
            disableSaveBtn: true,
            defaultSettings: formData,
          });

          window.onbeforeunload = null;
        });
      } else {
        this.setState({ submitting: false });
      }
    });
  };

  groupVisibilityValidator = (rule, value, callback) => {
    if (value && value.length > 0) {
      callback();
    } else {
      callback(
        intl.get({
          id: 'code-assets.groupPermissions.containers.root.SelectAtLeastOne',
          defaultMessage: '该项至少选中一个',
        }),
      );
    }
  };

  groupAdminAccessVisibilityValidator = (rule, value, callback) => {
    if (value && value.length > 0) {
      callback();
    } else {
      callback(
        intl.get({
          id: 'code-assets.groupPermissions.containers.root.SelectAtLeastOne',
          defaultMessage: '该项至少选中一个',
        }),
      );
    }
  };

  render() {
    const { field } = this;
    const { init } = field;
    const { isAliasNameSuccess } = this.props;
    return (
      <>
        {this.state.loading ? (
          <ListLoading />
        ) : (
          <>
            <Perf page="Organization-Settings-Group Permissions" />
            {isAliasNameSuccess && (
              <>
                <Header
                  title={intl.get({
                    id: 'code-assets.groupPermissions.containers.root.CodeGroupSettings',
                    defaultMessage: '代码组设置',
                  })}
                />

                <Content>
                  <>
                    <Form
                      {...formItemLayout}
                      labelTextAlign="right"
                      className="settings-repos-form"
                      field={field}
                      onChange={this.formChange}
                    >
                      <Section
                        title={intl.get({
                          id: 'code-assets.groupPermissions.containers.root.CreateACodeGroup',
                          defaultMessage: '创建代码组',
                        })}
                      >
                        <Form.Item
                          label={intl.get({
                            id: 'code-assets.groupPermissions.containers.root.Role',
                            defaultMessage: '角色',
                          })}
                          labelTextAlign="left"
                        >
                          <Checkbox.Group
                            className="settings-repos-checkgroup"
                            {...init('group_creator_role')}
                          >
                            <Checkbox value={60} disabled>
                              {intl.get({
                                id: 'code-assets.groupPermissions.containers.root.EnterpriseAdministrator',
                                defaultMessage: '企业管理员',
                              })}
                            </Checkbox>
                            <Checkbox value={15}>
                              {intl.get({
                                id: 'code-assets.groupPermissions.containers.root.EnterpriseMember',
                                defaultMessage: '企业成员',
                              })}
                            </Checkbox>
                            <Checkbox value={5}>
                              {intl.get({
                                id: 'code-assets.groupPermissions.containers.root.ExternalMembersOfTheEnterprise',
                                defaultMessage: '企业外部成员',
                              })}
                            </Checkbox>
                          </Checkbox.Group>
                        </Form.Item>
                        <Form.Item
                          label={intl.get({
                            id: 'code-assets.groupPermissions.containers.root.Openness',
                            defaultMessage: '公开性',
                          })}
                          labelTextAlign="left"
                        >
                          <Checkbox.Group
                            className="settings-repos-checkgroup"
                            itemDirection="ver"
                            {...init('group_visibility_level', {
                              rules: [
                                {
                                  validator: this.groupVisibilityValidator,
                                },
                              ],
                            })}
                          >
                            <Checkbox value={0}>
                              {intl.get({
                                id: 'code-assets.groupPermissions.containers.root.AllowPrivate',
                                defaultMessage: '允许私有',
                              })}

                              <span className="settings-repos-form-tips">
                                {intl.get({
                                  id: 'code-assets.groupPermissions.containers.root.AccessOnlyToCodeGroup',
                                  defaultMessage: '仅代码组成员可访问',
                                })}
                              </span>
                            </Checkbox>
                            <Checkbox value={10}>
                              {intl.get({
                                id: 'code-assets.groupPermissions.containers.root.AllowEnterpriseVisibility',
                                defaultMessage: '允许企业可见',
                              })}

                              <span className="settings-repos-form-tips">
                                {intl.get({
                                  id: 'code-assets.groupPermissions.containers.root.EnterpriseMembersCanAccess',
                                  defaultMessage: '企业内成员可访问',
                                })}
                              </span>
                            </Checkbox>
                          </Checkbox.Group>
                        </Form.Item>
                      </Section>
                      <Section
                        title={intl.get({
                          id: 'code-assets.groupPermissions.containers.root.AdjustGroupPublicity',
                          defaultMessage: '调整组公开性',
                        })}
                      >
                        <Form.Item>
                          <Checkbox.Group
                            itemDirection="ver"
                            className="settings-repos-checkgroup"
                            {...init('group_admin_access_visibility', {
                              rules: [
                                {
                                  validator: this.groupAdminAccessVisibilityValidator,
                                },
                              ],
                            })}
                          >
                            <Checkbox value={0}>
                              {intl.get({
                                id: 'code-assets.groupPermissions.containers.root.AllowTheCodeGroupAdministrator',
                                defaultMessage: '允许代码组管理员调整公开性为私有',
                              })}
                            </Checkbox>
                            <Checkbox value={10}>
                              {intl.get({
                                id: 'code-assets.groupPermissions.containers.root.AllowTheCodeGroupAdministrator.1',
                                defaultMessage: '允许代码组管理员调整公开性为企业可见',
                              })}
                            </Checkbox>
                          </Checkbox.Group>
                        </Form.Item>
                      </Section>

                      <Section
                        title={intl.get({
                          id: 'code-assets.groupPermissions.containers.root.DeleteACodeGroup',
                          defaultMessage: '删除代码组',
                        })}
                      >
                        <Form.Item>
                          <Checkbox.Group
                            itemDirection="ver"
                            className="settings-repos-checkgroup"
                            {...init('group_admin_operation')}
                          >
                            <Checkbox value={1}>
                              {intl.get({
                                id: 'code-assets.groupPermissions.containers.root.AllowGroupAdministratorsToDelete',
                                defaultMessage: '允许组管理员删除代码组',
                              })}
                            </Checkbox>
                          </Checkbox.Group>
                        </Form.Item>
                      </Section>
                      <Form.Item>
                        <Button
                          loading={this.state.submitting}
                          type="primary"
                          onClick={this.handleSave}
                          disabled={this.state.disableSaveBtn}
                        >
                          {intl.get({
                            id: 'code-assets.groupPermissions.containers.root.Save',
                            defaultMessage: '保存',
                          })}
                        </Button>
                      </Form.Item>
                    </Form>
                  </>
                </Content>
              </>
            )}
          </>
        )}
      </>
    );
  }
}

export default connect(
  (state) => state.organization.settings.groupPermissions,
  (dispatch) => bindActionCreators(actions, dispatch),
)(Root);
